package com.lcf.framework.permission;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.utils.UserUtils;
import com.lcf.system.entity.SysUser;
import com.lcf.system.enums.SysRoleEnum;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 描述：自定义权限验证接口扩展
 *
 * @author lcf
 * @since 2025/2/21 23:48
 */
@Component
public class StpInterfaceImpl implements StpInterface {
    /**
     * 返回此 loginId 拥有的权限列表
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        if (UserUtils.isPlatformAdmin()) {
            return List.of("*");
        }

        //角色编码列表
        List<String> roleCodeList = getRoleList(loginId, loginType);
        if (CollectionUtil.isEmpty(roleCodeList)) {
            return Collections.emptyList();
        }

        SysRoleEnum sysRoleEnum = Arrays.stream(SysRoleEnum.values()).filter(role -> roleCodeList.contains(role.name())).findAny().orElse(null);
        return sysRoleEnum == null ? Collections.emptyList() :sysRoleEnum.getPermissionList();
    }

    /**
     * 返回此 loginId 拥有的角色列表
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        if (UserUtils.isPlatformAdmin()) {
            return List.of("*");
        }

        SysRoleEnum roleEnum = Db.lambdaQuery(SysUser.class)
                .eq(SysUser::getId, loginId)
                .one()
                .getRoleCode();

        return Collections.singletonList(roleEnum.name());
    }
}
